<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Controller\AbstractController;
use App\Model\Article;
use App\Model\ArticleLike;
use App\Model\Comment;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;

#[Controller]
class ArticleController extends AbstractController
{
    #[GetMapping(path: '/api/article/list')]
    public function list()
    {
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $keyword = $this->request->input('keyword', '');
        $list = Article::query()
            ->select('id', 'user_id', 'user_id as userId', 'category_id', 'category_id as categoryId', 'title', 'summary', 'content', 'content_md as contentMd', 'cover', 'create_time as createTime', 'read_type', 'is_stick as isStick', 'status', 'quantity', 'create_time as createTime')
            ->when($keyword, function ($query) use ($keyword) {
                $query->where('title', 'like', '%' . $keyword . '%')->orWhere('summary', 'like', '%' . $keyword . '%');
            })->with(['tags', 'category', 'user'])->forPage($pageNum, $pageSize)->get();
        // 添加分类名称到原数组同级
        foreach ($list as &$article) {
            $article->categoryName = $article->category->name;
            $article->categoryId = $article->category->id;
            $article->commentNum = null;
            $article->likeNum = null;
            unset($article->category); // 可选：移除整个 category 对象
            $article->avatar = $article->user->avatar;
            $article->nickname = $article->user->nickname;
            unset($article->user); // 可选：移除整个 user 对象
        }
        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = Article::query()->count();
        $data['records'] = $list;
        return success($data);
    }

    #[GetMapping(path: '/api/article/detail/{id}')]
    public function detail($id)
    {
        $article = Article::query()->select('id', 'user_id', 'user_id as userId', 'category_id', 'category_id as categoryId', 'title', 'summary', 'content', 'content_md as contentMd', 'cover', 'create_time as createTime', 'read_type', 'is_stick as isStick', 'is_original as isOriginal', 'original_url as originalUrl', 'status', 'quantity')
            ->where('id', $id)
            ->with(['tags', 'category', 'user'])
            ->first();
        $article->avatar = $article->user->avatar;
        $article->nickname = $article->user->nickname;
        $article->commentNum = Comment::query()->where('article_id', $id)->count();
        $article->likeNum = ArticleLike::query()->where('article_id', $id)->count();
        $article->isLike = ArticleLike::query()->where('user_id', 1)->where('article_id', $id)->count() > 0;
        return success($article);
    }

    #[GetMapping(path: '/api/article/getCarousels')]
    public function getCarousels()
    {
        $list = Article::query()
            ->select('id', 'user_id', 'user_id as userId', 'category_id', 'category_id as categoryId', 'title', 'summary', 'content', 'content_md as contentMd', 'cover', 'create_time as createTime', 'read_type', 'is_stick as isStick', 'status', 'quantity', 'create_time as createTime')
            ->where('is_carousel', 1)
            ->with(['tags', 'category', 'user'])->get();
        // 添加分类名称到原数组同级
        foreach ($list as &$article) {
            $article->categoryName = $article->category->name;
            $article->categoryId = $article->category->id;
            $article->commentNum = null;
            $article->likeNum = null;
            unset($article->category); // 可选：移除整个 category 对象
            $article->avatar = $article->user->avatar;
            $article->nickname = $article->user->nickname;
            unset($article->user); // 可选：移除整个 user 对象
        }
        return success($list);
    }

    #[GetMapping(path: '/api/article/getRecommends')]
    public function getRecommends()
    {
        // return success();
        $list = Article::query()
            ->select('id', 'user_id', 'user_id as userId', 'category_id', 'category_id as categoryId', 'title', 'summary', 'content', 'content_md as contentMd', 'cover', 'create_time as createTime', 'read_type', 'is_stick as isStick', 'status', 'quantity', 'create_time as createTime')
            ->where('is_recommend', 1)
            ->with(['tags', 'category', 'user'])->get();
        // 添加分类名称到原数组同级
        foreach ($list as &$article) {
            $article->categoryName = $article->category->name;
            $article->categoryId = $article->category->id;
            $article->commentNum = null;
            $article->likeNum = null;
            unset($article->category); // 可选：移除整个 category 对象
            $article->avatar = $article->user->avatar;
            $article->nickname = $article->user->nickname;
            unset($article->user); // 可选：移除整个 user 对象
        }
        return success($list);
    }

    #[GetMapping(path: '/api/article/archive')]
    public function archive()
    {
        // 按年分组并保留年份
        $list = Article::query()
            ->select(Db::raw('YEAR(create_time) as year'), Db::raw("JSON_ARRAYAGG(
                JSON_OBJECT(
                    'id', id,
                    'title', title,
                    'createTime', create_time
                )
            ) as posts"))->groupBy('year')->get()->map(function ($item) {
                $item->posts = json_decode($item->posts, true);
                return $item;
            });
        return success($list);
    }

    #[GetMapping(path: '/api/article/categories')]
    public function categories()
    {
        $list = Article::query()
            ->select('category_id', Db::raw("JSON_ARRAYAGG(
                JSON_OBJECT(
                    'id', id,
                    'title', title,
                    'createTime', create_time
                )
            ) as posts"))->with('category')->groupBy('category_id')->get()->map(function ($item) {
                $item->name = $item->category->name;
                unset($item->category);
                $item->posts = json_decode($item->posts, true);
                return $item;
            });
        return success($list);
    }
}
